package com.chen.demo;

import com.sun.org.apache.regexp.internal.RE;

import java.util.HashMap;
import java.util.Map;

/**
 * 用于getter和setter当前线程的用户信息
 */
public class BaseContextUtil {
    //可继承的ThreadLocal，ThreadLocal为每个使用该变量的线程提供独立的变量副本，保证线程的隔离性
    private static InheritableThreadLocal<Map<String,Object>>threadLocal =new InheritableThreadLocal<>();
    //常量
    private static final String LOGIN_USER= "LOGIN_USER";
    private static void set(String key, Object value){
        Map<String, Object> map = threadLocal.get();
        if (map==null){
            map=new HashMap<>();
            threadLocal.set(map);
        }
        map.put(key,value);
    }

    private static Object get(String key){
        Map<String, Object> map = threadLocal.get();
        if (map==null){
            map=new HashMap<>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void setLoginUser(LoginUser loginUser){
        set(LOGIN_USER,loginUser);
    }
    public static LoginUser getLoginUser(){
        return (LoginUser) get(LOGIN_USER);
    }
    public static User getUser(){
        return getLoginUser().getUser();
    }
    public static Long getUserId(){
        return getUser().getId();
    }
}
